package com.randy.recyclerviews.modal;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.randy.recyclerviews.R;
import com.randy.recyclerviews.adapter.AbstractLoadMoreModel;
import com.randy.recyclerviews.adapter.UniversalAdapter;

/**
 * @author xudong
 * @since 2017/2/21
 */

public class LoadMoreItemModel
        extends AbstractLoadMoreModel<LoadMoreItemModel.ViewHolder> {

    private ObjectAnimator loadingAnimator;

    @Override
    public int getLayoutRes() {
        return R.layout.layout_common_load_more;
    }

    @Override
    public void onLoadMoreStart(@NonNull ViewHolder holder) {
        holder.loadMoreText.setText("正在加载...");
        showLoading(holder);

    }

    public void showLoading(ViewHolder holder) {
        if (loadingAnimator != null) loadingAnimator.cancel();
        holder.loadMoreIcon.setVisibility(View.VISIBLE);

        loadingAnimator = ObjectAnimator.ofFloat(holder.loadMoreIcon,
                View.ROTATION, 0, 360);
        loadingAnimator.setRepeatCount(ValueAnimator.INFINITE);
        loadingAnimator.setDuration(600);
        loadingAnimator.setRepeatMode(ValueAnimator.RESTART);
        loadingAnimator.start();
    }

    @Override
    public void onLoadMoreComplete(@NonNull ViewHolder holder) {
        holder.loadMoreText.setText("点击加载更多");

        if (loadingAnimator != null) loadingAnimator.cancel();
        holder.loadMoreIcon.setVisibility(View.GONE);
    }

    @Override
    public void onLoadMoreFailed(@NonNull ViewHolder holder) {
        holder.loadMoreText.setText("点击重试");

        if (loadingAnimator != null) loadingAnimator.cancel();
        holder.loadMoreIcon.setVisibility(View.GONE);
    }

    @NonNull
    @Override
    public UniversalAdapter.IViewHolderCreator<ViewHolder> getViewHolderCreator() {
        return new UniversalAdapter.IViewHolderCreator<ViewHolder>() {
            @NonNull
            @Override
            public ViewHolder create(@NonNull View view) {
                return new ViewHolder(view);
            }
        };
    }

    public class ViewHolder extends UniversalAdapter.ViewHolder {
        public TextView loadMoreText;
        public ImageView loadMoreIcon;

        public ViewHolder(View itemView) {
            super(itemView);
            loadMoreText = itemView.findViewById(R.id.loading_more_text);
            loadMoreIcon = itemView.findViewById(R.id.loading_more_icon);
        }
    }
}
